//
//  CartoonCollectionViewController.m
//  Cartoon
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonCollectionViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "CartoonSet.h"
#import "CartoonCollectionTableViewCell.h"
#import "CartoonDetailsViewController.h"
#import "CollectViewController.h"
#import "CartoonMyDownLoadViewController.h"
#import "CartoonCollectionAlreadReading.h"
#import "AlreadyReading.h"
#import "CartoonReadingViewController.h"
#import "CartoonCollectionCustomSectionHeanerView.h"

@interface CartoonCollectionViewController ()<UITableViewDataSource,UITableViewDelegate,CartoonCollectionTableViewCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *lockButton;

@property (nonatomic, strong) NSMutableArray *alreadyReadingArr;
@end

@implementation CartoonCollectionViewController
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 / 255.0 alpha:1];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    // 调整导航栏字的颜色
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
    
    self.alreadyReadingArr = [NSMutableArray array];
    
    
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"33"]];
    [self.view addSubview:image];
    image.frame = CGRectMake(0, 64, 375 *WIDTH, 220 *HEIGHT);
    
    UIButton *collectionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    collectionButton.frame = CGRectMake(0, 30 *HEIGHT, SelfViewWidth, SelfViewHeight / 8);
    UILabel *collectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(-112 * WIDTH, 60 * HEIGHT, SelfViewWidth, 30 * HEIGHT)];
    collectionLabel.textAlignment = NSTextAlignmentCenter;
    collectionLabel.font = [UIFont boldSystemFontOfSize:20 * WIDTH];
    collectionLabel.text = @"我的收藏";
    [collectionButton addTarget:self action:@selector(open:) forControlEvents:UIControlEventTouchUpInside];
    collectionLabel.textColor = [UIColor whiteColor];
    [collectionButton addSubview:collectionLabel];
    [self.view addSubview:collectionButton];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    NSString *timestamp = [formatter stringFromDate:[NSDate date]];
    if ([timestamp isEqualToString:@"2015-11-22 19:12"]) {
    UIButton *downLoadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    downLoadButton.frame = CGRectMake(26 * WIDTH, 64 + 70 * HEIGHT, SelfViewWidth / 4, SelfViewHeight / 8);

    [downLoadButton setTitle:@"继续下载" forState:UIControlStateNormal];
    [downLoadButton addTarget:self action:@selector(downLoadButton:) forControlEvents:UIControlEventTouchUpInside];
    downLoadButton.font = [UIFont boldSystemFontOfSize:20 * WIDTH];
    downLoadButton.tintColor = [UIColor whiteColor];
    [self.view addSubview:downLoadButton];
    
    UIButton *alreadyDownLoadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    alreadyDownLoadButton.frame = CGRectMake(- 20 * WIDTH, 64 + collectionButton.frame.size.height + 60 * HEIGHT, SelfViewWidth / 2, SelfViewHeight / 8);

    [alreadyDownLoadButton setTitle:@"已经下载" forState:UIControlStateNormal];
    [alreadyDownLoadButton addTarget:self action:@selector(alreadyDownLoadButton:) forControlEvents:UIControlEventTouchUpInside];
    alreadyDownLoadButton.font = [UIFont boldSystemFontOfSize:20 *WIDTH];
    alreadyDownLoadButton.tintColor = [UIColor whiteColor];
    [self.view addSubview:alreadyDownLoadButton];
    
    }
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + SelfViewHeight / 3, SelfViewWidth, SelfViewHeight - 64 - SelfViewHeight / 3 - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[CartoonCollectionTableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableView registerClass:[CartoonCollectionCustomSectionHeanerView class] forHeaderFooterViewReuseIdentifier:@"cellHeader"];
    
    
    UIImageView *lockImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SelfViewWidth / 2 - 40, SelfViewHeight / 2 - 40, 80, 80)];
    [lockImageView setImage:[UIImage imageNamed:@"suo"]];
    self.lockButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.lockButton.frame = self.view.bounds;
    self.lockButton.backgroundColor = [UIColor whiteColor];
    [self.lockButton addTarget:self action:@selector(touchID) forControlEvents:UIControlEventTouchUpInside];
    [self.lockButton addSubview:lockImageView];
    [self.view addSubview:_lockButton];
//    _lockButton.backgroundColor = [UIColor blackColor];

    
    BOOL isOpen = [[FMDB shareFMDB].db open];

    if (isOpen == NO) {
        NSLog(@"NO == %d",isOpen);
        
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table cartoonset (myswitch bool primary key)"]];
        NSLog(@"创建是否成功 :%d",creatResult);
        
        FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM cartoonset"];
        
        
        if (!set.next) {
            _lockButton.hidden = YES;
            
        }else{
            _lockButton.hidden = ![set boolForColumn:@"myswitch"];
            NSLog(@"set boolForColumn: = %d",[set boolForColumn:@"myswitch"]);
        }
    }


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lockButtonHidden:) name:@"lock" object:nil];
    
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 64 + SelfViewHeight / 3, SelfViewWidth, SelfViewHeight - 64 - SelfViewHeight / 3 - 49)];
    label.text = @"您还没有阅读记录哦";
    label.textAlignment = NSTextAlignmentCenter;
    label.tag = 101;
    label.hidden = YES;
    [self.view addSubview:label];
    
    [self handler];
    
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    
    
    BOOL result = [[FMDB shareFMDB].db open];
    
    if (result == NO) {
        NSLog(@"NO == %d",result);
        
    }else{
     
    }
    CartoonCollectionAlreadReading *CartoonCollectionAlreadReading = self.alreadyReadingArr[indexPath.row];
    [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"delete from CartoonCollectionAlreadReading where image = '%@'",CartoonCollectionAlreadReading.image]];
        
    [self.alreadyReadingArr removeObjectAtIndex:indexPath.row];
        
    [self.tableView reloadData];
        
    }
}


- (void)alreadyDownLoadButton:(UIButton *)btn
{
    CartoonMyDownLoadViewController *downVC = [[CartoonMyDownLoadViewController alloc] init];
    downVC.whereAction = @"已下载";
    [self.navigationController pushViewController:downVC animated:YES];
}
- (void)downLoadButton:(UIButton *)btn
{
    
    CartoonMyDownLoadViewController *downVC = [[CartoonMyDownLoadViewController alloc] init];
    downVC.whereAction = @"继续下载";
    [self.navigationController pushViewController:downVC animated:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    CartoonCollectionCustomSectionHeanerView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cellHeader"];
   
    
    
    // 可以使用tag, 方便的在按钮点击方法中, 获取点击到的section.
    view.myButton.tag = section + 1000;
    [view.myButton setTitle:@"清除历史记录" forState:UIControlStateNormal];
    
    view.myButton.titleLabel.textAlignment = NSTextAlignmentRight;
    [view.myButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    view.myLabel.text = @"阅读记录";
    return view;
}
- (void)buttonAction:(UIButton *)btn
{
    BOOL result = [[FMDB shareFMDB].db open];
    
    if (result == NO) {
        NSLog(@"NO == %d",result);
        
    }else{
        
    }
    for (CartoonCollectionAlreadReading *CartoonCollectionAlreadReading in self.alreadyReadingArr) {
        
    [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"delete from CartoonCollectionAlreadReading where image = '%@'",CartoonCollectionAlreadReading.image]];
    
    }
    [self.alreadyReadingArr removeAllObjects];
    [self.view viewWithTag:101].hidden = NO;
    self.tableView.hidden = YES;
    [self.tableView reloadData];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    return @"阅读记录";
//}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.alreadyReadingArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartoonCollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    CartoonCollectionAlreadReading *read = self.alreadyReadingArr[indexPath.row];
    cell.delegate = self;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:read.image] placeholderImage:[UIImage imageNamed:@"5"]];
    cell.myNameLabel.text = read.name;
    
    return cell;
}
- (void)handler
{
    
    self.alreadyReadingArr = [NSMutableArray array];
    BOOL result = [[FMDB shareFMDB].db open];
    
    if (result == NO) {
        NSLog(@"NO == %d",result);
        
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonCollectionAlreadReading (image text primary key, name text , lated_seqno text , comic_id text)"]];
        
        NSLog(@"创建是否成功 :%d",creatResult);
        
    }
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonCollectionAlreadReading"];
    
    
    while ([set next]) {
        CartoonCollectionAlreadReading *read = [[CartoonCollectionAlreadReading alloc]init];
        read.name = [set stringForColumn:@"name"];
        read.image = [set stringForColumn:@"image"];
        read.lated_seqno = [set stringForColumn:@"lated_seqno"];
        read.comic_id = [set stringForColumn:@"comic_id"];
        [self.alreadyReadingArr addObject:read];
    }
    if (self.alreadyReadingArr.count == 0) {
        [self.view viewWithTag:101].hidden = NO;
        self.tableView.hidden = YES;
    }
    [self.tableView reloadData];
}

- (void)continueLookButtonAction:(UIButton *)btn cell:(UITableViewCell *)cell
{
    BOOL result = [[FMDB shareFMDB].db open];
    
    if (result == NO) {
        NSLog(@"NO == %d",result);
        
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table AlreadyReading (cartoonID text primary key, cartoonPage text)"]];
        
        NSLog(@"创建是否成功 :%d",creatResult);
        
    }
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
    NSMutableArray *array = [NSMutableArray array];
    
    CartoonCollectionAlreadReading *CartoonCollectionAlreadReading = self.alreadyReadingArr[[self.tableView indexPathForCell:cell].row];
    
    while ([set next]) {
        
        AlreadyReading *read = [[AlreadyReading alloc]init];
        read.cartoonID = [set stringForColumn:@"cartoonID"];
        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:CartoonCollectionAlreadReading.comic_id]) {
            [array addObject:read];
            break;
        }
    }
    if (array.count > 0) {
        AlreadyReading *read = array[0];
        CartoonReadingViewController *reading = [[CartoonReadingViewController alloc] init];
        
        reading.page = [CartoonCollectionAlreadReading.lated_seqno integerValue] - [[[read.cartoonID componentsSeparatedByString:@"/"] firstObject] integerValue];
        reading.comic_id = CartoonCollectionAlreadReading.comic_id;
        reading.cover_url = CartoonCollectionAlreadReading.image;
        reading.bigTitle = CartoonCollectionAlreadReading.name;
        reading.lated_seqno = CartoonCollectionAlreadReading.lated_seqno;
        
        [self.navigationController pushViewController:reading animated:YES];
        
    }
}



- (void)lockButtonHidden:(NSNotification *)noti
{
    if ([noti.object isEqualToString:@"1"]) {NSLog(@"显示");
        self.lockButton.hidden = NO;
    }else{NSLog(@"隐藏");
       self.lockButton.hidden = YES;
    }
    
}

- (void)touchID
{
    LAContext *context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"TouchID";
    
    NSError *error = nil;
    
    // 判断支持 Touch ID
    // LAPolicy只有一个值: LAPolicyDeviceOwnerAuthenticationWithBiometrics
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]) {
        
        // 验证身份
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:NSLocalizedString(@"登录", nil) reply:^(BOOL success, NSError *error) {
            if (success) {
                NSLog(@"TouchID deblocking success");
                [self showInfoWithmessage:@"验证成功可进入"];
                self.lockButton.hidden = YES;
                [self.view sendSubviewToBack:_lockButton];
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"lock" object:@"0"];
            }
            else{
                if (error.code == kLAErrorUserFallback) {
                    NSLog(@"use passWord");
//                    [self passWord];
//                    [self showInfoWithmessage:@"选择输入密码"];
                }
                else if (error.code == kLAErrorSystemCancel)
                {
//                    [self showInfoWithmessage:@"系统切换到其他应用"];
                }
                else if (error.code == kLAErrorUserCancel)
                {
                    NSLog(@"cancel use TouchID");
//                    [self showInfoWithmessage:@"用户取消验证"];
                }
                // 不支持Touch ID 技术
                else
                {
                    NSLog(@"fail");
//                    [self showInfoWithmessage:@"解锁失败"];
                }
            }
            
        }];
    }
    else
    {
        if (error.code == LAErrorTouchIDNotEnrolled) {
//            [self showInfoWithmessage:@"未注册Touch ID"];
        }
        else if (error.code == LAErrorPasscodeNotSet){
//            [self showInfoWithmessage:@"未设置密码"];
        }
        else{
//            [self showInfoWithmessage:@"不支持Touch ID"];
        }
    }
}
- (void)passWord
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入密码" preferredStyle:1];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
        
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.placeholder = @"请输入正确密码";
        textField.clearButtonMode = UITextFieldViewModeAlways;
        textField.secureTextEntry = YES;
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
    
}

- (void)open:(UIButton *)btn
{
    CollectViewController *collect = [[CollectViewController alloc] init];
    [self.navigationController pushViewController:collect animated:NO];
   

}
- (void)showInfoWithmessage:(NSString *)message
{
    NSLog(@"%@",message);
    if ([message isEqualToString:@"验证成功可进入"]) {
        self.lockButton.hidden = YES;
        
        NSLog(@"self.lockButton.hidden = 验证成功可进入 %d",self.lockButton.hidden);
    }
//    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
//    [alert addAction:okAction];
 
    
    
//    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"缓存" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"清除", nil];
//    [alertView show];
    
   
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CartoonDetailsViewController *detail = [[CartoonDetailsViewController alloc] init];
    CartoonCollectionAlreadReading *CartoonCollectionAlreadReading = self.alreadyReadingArr[indexPath.row];
    detail.idtext = CartoonCollectionAlreadReading.comic_id;
    
    [self.navigationController pushViewController:detail animated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.view viewWithTag:101].hidden = YES;
    self.tableView.hidden = NO;
    [self handler];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
